import { logout, refreshToken } from '@/api/login'
import { getInfo } from '@/api/login'
import IngotCookie from '@/core/utils/cookie'
import { enums } from '@/core/config'
import router from '@/router'

const jumpLoginPage = () => {
  router.push({ name: 'Login' })
}

const user = {
  state: {
    name: '',
    avatar: '',
    roles: [],
    loginName: '',
    redirectUri: '',
    authToken: {
      access_token: '',
      expires_in: '',
      timestamp: ''
    },
    refreshToken: {
      refresh_token: '',
      expires_in: '',
      timestamp: ''
    }
  },
  getters: {
    getLoginName: state => {
      state.loginName = IngotCookie.get(enums.USER.LOGIN_NAME)
      return state.loginName
    },
    getRefreshToken: state => {
      if (!state.refreshToken) {
        state.refreshToken = IngotCookie.get(enums.USER.REFRESH_TOKEN)
          ? JSON.parse(IngotCookie.get(enums.USER.REFRESH_TOKEN))
          : {}
      }
      return state.refreshToken.refresh_token
    },
    getAccessToken: state => {
      if (!state.authToken || !state.authToken.access_token || state.authToken.access_token.length === 0) {
        state.authToken = IngotCookie.get(enums.USER.AUTH_TOKEN)
          ? JSON.parse(IngotCookie.get(enums.USER.AUTH_TOKEN))
          : {}
      }
      // console.log("authToken",state.authToken)
      return state.authToken.access_token
    },
    getRedirectUri: state => {
      if (!state.redirectUri) {
        state.redirectUri = IngotCookie.get(enums.USER.REDIRECT_URI)
          ? decodeURI(IngotCookie.get(enums.USER.REDIRECT_URI))
          : process.env.VUE_APP_WEB
      }
      return state.redirectUri
    }
  },
  mutations: {
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    updateUserInfo(state, loginName) {
      state.loginName = loginName
      IngotCookie.set({
        key: enums.USER.LOGIN_NAME,
        value: loginName
      })
    },
    updateAuthToken(state, authToken) {
      // console.log("updateAuthToken",state)
      // console.log("updateAuthToken",authToken)
      const timestamp = new Date().getTime()
      // https://github.com/js-cookie/js-cookie/wiki/Frequently-Asked-Questions#expire-cookies-in-less-than-a-day
      let expires = 2 / 24
      const isRemember = !!IngotCookie.get(enums.USER.REMEMBER_ME)

      if (isRemember) {
        expires = 7
      }

      if (authToken.access_token) {
        const accessToken = {
          access_token: authToken.access_token,
          expires_in: authToken.access_token_expire,
          timestamp: timestamp
        }
        state.authToken = accessToken
        console.log("state.authToken",state.authToken)
        IngotCookie.set({
          key: enums.USER.AUTH_TOKEN,
          value: authToken,
          expires: expires
        })
        // console.log("state.authToken",state.authToken)

        // console.log("IngotCookie",IngotCookie.get(enums.USER.AUTH_TOKEN))
      }

      if (authToken.refresh_token) {
        const refreshToken = {
          refresh_token: authToken.refresh_token,
          expires_in: authToken.access_token_expire,
          timestamp: timestamp
        }
        state.refreshToken = refreshToken
        IngotCookie.set({
          key: enums.USER.REFRESH_TOKEN,
          value: refreshToken,
          expires: expires
        })
        // console.log("IngotCookie",IngotCookie.get(enums.USER.REFRESH_TOKEN))
      }
    },
    deleteUserInfo(state) {
      IngotCookie.remove({
        key: enums.USER.LOGIN_NAME
      })
      state.loginName = ''
      IngotCookie.remove({
        key: enums.USER.REMEMBER_ME
      })
      state.rememberMe = false
    },
    deleteAuthToken(state) {
      state.authToken = {}
      IngotCookie.remove({
        key: enums.USER.AUTH_TOKEN
      })
    },
    updateRedirectUri(state, redirectUri) {
      state.redirectUri = redirectUri
      IngotCookie.set({
        key: enums.USER.REDIRECT_URI,
        value: redirectUri
      })
    }
  },

  actions: {
    get_access_token({ commit, state }, cb) {
      console.log("get_access_token",state)
      if (!state.authToken || !state.authToken.access_token || state.authToken.access_token === '') {
        state.authToken = IngotCookie.get(enums.USER.AUTH_TOKEN)
          ? JSON.parse(IngotCookie.get(enums.USER.AUTH_TOKEN))
          : {}
      }

      if (state.authToken.access_token) {
        // 判断是否需要续租
        const expire = state.authToken.expires_in || 120 * 60 * 1000
        if (
          new Date().getTime() - state.authToken.timestamp >
          expire
        ) {
          refreshToken().then(res => {
            console.info('refresh token res:', res.data)
            commit('updateAuthToken', res.data)
          }).catch(() => {
            commit('deleteAuthToken')
            jumpLoginPage()
          })
        }
      }
      cb && cb(state.authToken.access_token)
    },
    update_remember_me({ commit }) {
      commit('updateRememberMe')
    },
    update_user_info({ commit }, loginName) {
      commit('updateUserInfo', loginName)
    },
    delete_user_info({ commit }, loginName) {
      commit('deleteUserInfo', loginName)
      commit('deleteAuthToken')
      commit('deleteRememberMe')
    },
    update_auth_token({ commit }, authToken) {
      // console.log("commit",commit)
      commit('updateAuthToken', authToken)
      if (authToken.redirect_url && authToken.redirect_url.length !== 0) {
        commit('updateRedirectUri', authToken.redirect_url)
      }
    },
    update_redirect_uri({ commit }, redirectUri) {
      commit('updateRedirectUri', redirectUri)
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          if (data.role_list && data.role_list.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.role_list)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.username)
          commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      console.log('登出')
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_ROLES', [])
          commit('deleteAuthToken')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        // console.log('退出',resolve)
        IngotCookie.remove({key:'pageOne-data'})
        commit('set_page_index',1)
        commit('SET_ROLES', [])
        commit('deleteAuthToken')
        resolve()
      })
    }
  }
}

export default user
